<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/3/28
 * Time: 09:53
 */

namespace app\admin\controller;


use app\admin\logic\SendLogic;
use app\common\controller\Backend;
use app\common\utils\Constant;
use fast\Tree;
use think\Db;
use think\Exception;

/**
 * 用户管理
 * Class User
 * @package app\admin\controller
 */
class User extends Backend
{
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax())
        {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where(array('user_type'=>Constant::USER_TYPE_GENERAL))
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->where(array('user_type'=>Constant::USER_TYPE_GENERAL))
                ->field(['password', 'salt', 'token'], true)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 冻结功能
     * @return string
     */
    public function freeze($ids=''){
        if ($this->request->isAjax())
        {
            Db::startTrans();
            try{
                $data = $this->request->post('row/a');
                if(!isset($data['rules'])){
                    $this->error('请勿非法提交！');
                }
                $user_node_list = model('UserNode')->where(array('user_id'=>$ids))->field('function_node_id')->select();
                $user_node_ids = [];
                foreach ($user_node_list as $key=>$value){
                    $user_node_ids[]=$value['function_node_id'];
                }
                $new_node_ids = [];
                model('UserNode')->where(array('user_id'=>$ids))->delete();
                if(!empty($data['rules'])){
                    model('User')->where(array('id'=>$ids))->setField('is_freeze',1);
                    $node_ids = explode(',',$data['rules']);
                    $new_node_ids = array_diff($node_ids,$user_node_ids);//node_ids中存在 $user_node_ids中不存在
                    $delete_node_ids = array_diff($user_node_ids,$node_ids);//$user_node_ids中存在 $node_ids中不存在
                    $user_node['user_id'] = $ids;
                    foreach ($node_ids as $key=>$value){
                        $user_node['function_node_id'] = $value;
                        model('UserNode')->insert($user_node);
                    }
                }else{
                    $delete_node_ids = $user_node_ids;
                    model('User')->where(array('id'=>$ids))->setField('is_freeze',0);
                }
                //添加操作记录
                $admin_user_id = $this->auth->id;
                if(count($delete_node_ids) > 0){
                    $delete_node_ids_str = implode(',',$delete_node_ids);
                    $type = Constant::FREEZE_OPERATION_TYPE_REMOVE_FREEZE;
                    $this->addFreezeLog($type,$delete_node_ids_str,$ids,$admin_user_id);
                }
                if(count($new_node_ids) > 0){
                    $new_node_ids_str = implode(',',$new_node_ids);
                    $type = Constant::FREEZE_OPERATION_TYPE_FREEZE;
                    $this->addFreezeLog($type,$new_node_ids_str,$ids,$admin_user_id);
                }
                Db::commit();
                $this->success('操作成功！');
            }catch (Exception $e){
                Db::rollback();
                $this->error('冻结失败！');
            }
        }
        $this->assignconfig('user_id',$ids);
        $this->view->assign('user_id',$ids);
        return $this->view->fetch();
    }

    private function addFreezeLog($operation_type,$node_ids,$user_id,$operation_id){
        $log['operation_type'] = $operation_type;
        $log['node_ids'] = $node_ids;
        $log['user_id'] = $user_id;
        $log['operation_id'] = $operation_id;
        model('FreezeLog')->insert($log);
    }

    /**
     * 读取用户冻结功能列表
     *
     * @internal
     */
    public function node_list()
    {
        $this->loadlang('auth/group');

        $model = model('User');
        $id = $this->request->post("id");
        $current_user = NULL;
        if ($id)
        {
            $current_user = $model->get($id);
        }
        if (!$id || $current_user)
        {
            $id = $id ? $id : NULL;
            $ruleList = collection(model('FunctionNode')->select())->toArray();
            //读取用户所有冻结节点列表
            $current_rule_ids = [];
            $node_list = model('UserNode')->where(array('user_id'=>$id))->field('function_node_id')->select();
            foreach ($node_list as $key=>$value){
                $current_rule_ids[] = $value['function_node_id'];
            }
            //当前所有正常规则列表
            $tree = Tree::instance()->init($ruleList);
            $tree->pidname = 'parent_id';

            $ruleList = $tree->getTreeList($tree->getTreeArray(0), 'name');
            $hasChildrens = [];
            foreach ($ruleList as $k => $v)
            {
                if ($v['haschild'])
                    $hasChildrens[] = $v['id'];
            }
            $nodelist = [];
            foreach ($ruleList as $k => $v)
            {
                $state = array('selected' =>in_array($v['id'], $current_rule_ids) && !in_array($v['id'], $hasChildrens));
                $nodelist[] = array('id' => $v['id'], 'parent' => $v['parent_id'] ? $v['parent_id'] : '#', 'text' => __($v['name']), 'type' => 'menu', 'state' => $state);
            }
            $this->success('', null, $nodelist);
        }
        else
        {
            $this->error(__('User not found'));
        }
    }

    /**
     * 上传头像图片
     */
    public function uploadImageFile(){
        $file = $this->request->file('file');
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'.DS.'image');
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            $host = "$protocol$_SERVER[HTTP_HOST]";
            if($info){
                $this->success('上传成功！','',['url' =>$host.'/uploads/image/' . $info->getSaveName()]);
            }else{
                // 上传失败获取错误信息
                $this->error($file->getError());
            }
        }else{
            $this->error('文件不存在！');
        }
    }

    public function test(){
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $host = "$protocol$_SERVER[HTTP_HOST]";
        echo  $host;
    }

    private function getRobotList(){
        $map['user_type'] = Constant::USER_TYPE_THE_ROBOT;
        $list = model('User')->where($map)->field('nickname,id')->select();
        $user_list = [];
        foreach ($list as $key=>$value){
            $user_list[$value['id']] = $value['nickname'];
        }
        return $user_list;
    }

    public function getStandardList(){
        $list = model('Standard')->select();
        return $list;
    }

    /**
     * 批量发送挑战记录
     * @return string
     */
    public function send(){
        if($this->request->isAjax()){
            $standard_id = $this->request->post('standard_id');
            $user_ids = $this->request->post('user_id/a');
            $logic = new SendLogic();
            $result = $logic->sendRedEnvelope($standard_id,$user_ids);
            $success = false;
            $msg = '';
            $data = [];
            switch ($result['status']){
                case 0:
                    $msg = '添加失败！';
                    $data = $result['error'];
                    break;
                case 1:
                    $msg = '添加成功！';
                    $success = true;
                    break;
                case 2:
                    $msg = $result['msg'];
                    break;
            }
            if($success){
                $this->success($msg,'',$data);
            }else{
                $this->error($msg,'',$data);
            }
        }
        $robot_list = $this->getRobotList();
        $this->view->assign('robot_list',$robot_list);
        return $this->view->fetch();
    }


    /**
     * 添加机器人
     * @return string
     */
    public function add(){
        if($this->request->isAjax()){
            $data = $this->request->post('row/a');
            $data['user_type'] = Constant::USER_TYPE_THE_ROBOT;
            if ($data)
            {
                $this->model->create($data);
                $this->success('添加成功');
            }
            $this->error('添加失败');
        }
        return $this->view->fetch();
    }

    /**
     * 修改机器人
     * @return string
     */
    public function edit($ids=''){
        $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        if($this->request->isAjax()){
            $data = $this->request->post('row/a');
            $data['user_type'] = Constant::USER_TYPE_THE_ROBOT;
            if ($data)
            {
                $row->save($data);
                $this->success('修改成功');
            }
            $this->error('修改失败');
        }
        $this->view->assign('row',$row);
        return $this->view->fetch();
    }

    /**
     * 机器人列表
     */
    public function robot_list(){
        if ($this->request->isAjax())
        {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where(array('user_type'=>Constant::USER_TYPE_THE_ROBOT))
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->where(array('user_type'=>Constant::USER_TYPE_THE_ROBOT))
                ->field('nickname,id')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 红包发送记录
     * @param string $ids
     * @return string|\think\response\Json
     */
    public function send_list($ids=''){
        if ($this->request->isAjax())
        {
            $this->model = model('RedEnvelope');
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $map['user_id'] = $ids;
            $total = $this->model
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $nickname = model('User')->where(array('id'=>$ids))->value('nickname');
            foreach ($list as $key=>&$value){
                $value['nickname'] = $nickname;
            }
            unset($value);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->assignconfig('user_id',$ids);
        return $this->view->fetch();
    }
}